import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Tag, Table } from '@teamix/ui';
import Pagination from 'components/commonPagination';
import { YunxiaoIcon } from '@alife/devops-ui';
import exceed from 'utils/apimap';
import utils from 'utils';
import ListEmpty from 'atComponents/ListEmpty';
import Detail from './detail';
import './index.scss';
import intl from '../../../../../../../../../../locale';

const prefix = 'webhook-history-dialog';
export default class GroupModal extends React.Component {
  static propTypes = {
    trigger: PropTypes.element,
    closeModal: PropTypes.func,
  };

  static defaultProps = {
    trigger: null,
    closeModal: () => {},
  };

  constructor(props) {
    super(props);

    this.state = {
      isModalOpen: false,
      tableData: [],
      isLoading: true,
      total: 0,
      page: 1,
      openRowKeys: [],
    };
  }

  static getDerivedStateFromProps(props) {
    if (props.trigger) {
      return {};
    }
    return {
      isModalOpen: props.isModalOpen,
    };
  }

  showModal = () => {
    this.setState({
      isModalOpen: true,
    });
  };

  componentDidMount() {
    this.getList(1);
  }

  // 获取敏感行为表
  getList = (page = 1) => {
    const { web_hook_id } = this.props;
    const { pathResource } = window.FORCE;
    this.setState({
      isLoading: true,
      openRowKeys: [],
    });

    exceed
      .forceFetch({
        api: 'project.webhook.history.list',
        params: {
          projectId: pathResource.id,
        },

        data: {
          web_hook_id,
          page,
          per_page: 10,
        },
      })
      .then((result) => {
        const { list } = result;
        const total = result.amount || 0;
        this.setState({
          tableData: list,
          isLoading: false,
          total,
          page,
        });
      });
  };

  onClose = () => {
    this.setState({
      isModalOpen: false,
    });

    this.props.closeModal();
  };

  expandedRowRender = (record) => {
    return <Detail record={record} getList={this.getList} />;
  };

  onRowOpen = (openRowKeys) => {
    this.setState({
      openRowKeys,
    });
  };

  renderId = (value, index, record) => {
    const isOk = record.responseStatus < 300 && record.responseStatus >= 200;
    return (
      <div className="content">
        <YunxiaoIcon
          type={isOk ? 'success-fill' : 'delete-fill'}
          style={{ color: isOk ? '#1DC11D' : '#e62412', marginRight: '4px' }}
        />

        <div className="table-cell-one-line" style={{ width: 290 }}>
          {value}
        </div>
        {record.retry && (
          <div>
            <Tag>
              {intl.get({
                id: 'code-assets.containers.historyModal.TryAgain',
                defaultMessage: '重试',
              })}
            </Tag>
          </div>
        )}
      </div>
    );
  };

  onPageNoChange = (page) => {
    this.getList(page);
  };

  render() {
    const { tableData, isLoading, total, page, openRowKeys } = this.state;
    return (
      <React.Fragment>
        {this.state.isModalOpen ? (
          <Dialog
            title={
              <div className={`${prefix}-title`}>
                <span className="title">
                  {intl.get({
                    id: 'code-assets.containers.historyModal.LastSentHistory',
                    defaultMessage: '最近发送历史',
                  })}
                </span>
                <span className="sub-title">
                  {intl.get({
                    id: 'code-assets.containers.historyModal.OnlyTheLastRecordsAre',
                    defaultMessage: '仅展示最近 100 条记录',
                  })}
                </span>
              </div>
            }
            visible
            style={{ width: 800 }}
            onCancel={this.onClose}
            onClose={this.onClose}
            footer={false}
            className={prefix}
          >
            <div className={`${prefix}-container`}>
              <Table
                className={`no-border-table ${prefix}-table`}
                hasBorder={false}
                dataSource={tableData}
                expandedRowRender={this.expandedRowRender}
                onRowOpen={this.onRowOpen}
                openRowKeys={openRowKeys}
                onRowClick={(record) => {
                  const curOpenRowKeys = [...openRowKeys];
                  const index = curOpenRowKeys.indexOf(record.id);
                  if (index > -1) {
                    curOpenRowKeys.splice(index, 1);
                  } else {
                    curOpenRowKeys.push(record.id);
                  }
                  this.setState({
                    openRowKeys: curOpenRowKeys,
                  });
                }}
                rowProps={() => {
                  return {
                    style: {
                      cursor: 'pointer',
                    },
                  };
                }}
                loading={isLoading}
                emptyContent={
                  <ListEmpty
                    content={intl.get({
                      id: 'code-assets.containers.historyModal.NoData',
                      defaultMessage: '暂无数据',
                    })}
                    imgType="search"
                    className="table-list-empty"
                  />
                }
                expandedRowIndent={[0, 0]}
              >
                <Table.Column
                  title={intl.get({
                    id: 'code-assets.containers.historyModal.RecordNumber',
                    defaultMessage: '记录编号',
                  })}
                  dataIndex="deliveryId"
                  className="deliveryId-col"
                  cell={this.renderId}
                  width={280}
                />

                <Table.Column
                  title={intl.get({
                    id: 'code-assets.containers.historyModal.SendingTime',
                    defaultMessage: '发送时间',
                  })}
                  dataIndex="sendTime"
                  className="time-col"
                  cell={utils.getBeautyTime}
                  width={170}
                />

                <Table.Column
                  title={intl.get({
                    id: 'code-assets.containers.historyModal.TimeConsuming',
                    defaultMessage: '耗时',
                  })}
                  className="consumer-col"
                  dataIndex="timeConsuming"
                  cell={(value) => `${value}ms`}
                  width={80}
                />
              </Table>
              <Pagination
                onChange={this.onPageNoChange}
                current={page}
                total={total}
                showJump={false}
                hideOnlyOnePage
              />
            </div>
          </Dialog>
        ) : null}
        {!!this.props.trigger &&
          React.cloneElement(this.props.trigger, { onClick: this.showModal })}
      </React.Fragment>
    );
  }
}
